package com.cskaoyan.controller;

import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.data.TopicDetailData;
import com.cskaoyan.bean.data.TopicListData;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.domain.MarketTopic;
import com.cskaoyan.service.SystemConfigService;
import com.cskaoyan.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("wx/topic")
public class WxTopicController {

    @Autowired
     TopicService topicService;

    @Autowired
    SystemConfigService systemConfigService;


    @RequestMapping("list")
    public BaseRespVo list(Integer page,Integer limit){
        List<TopicListData> topicListData = topicService.selectAllTopicList();
        CommonData data = new CommonData();
        data.setLimit(limit);
        data.setList(topicListData);
        data.setPage(page);
        int total=(int) topicListData.stream().count();
        data.setTotal(total);
        int pages=total%limit==0?total/limit:total/limit+1;
        data.setPages(pages);
        return BaseRespVo.ok(data);
    }

    @RequestMapping("/detail")
    public BaseRespVo detail(Integer id) {
        MarketTopic topic = topicService.selectTopicById(id);
        Integer[] goods = topic.getGoods();
        TopicDetailData data = new TopicDetailData(goods,topic);
        return BaseRespVo.ok(data);
    }

    @RequestMapping("/related")
    public BaseRespVo related(Integer id) {
        Map<String, Object> listWxConfig= systemConfigService.listWxConfig();
        Integer limit= Integer.valueOf(listWxConfig.get("market_wx_index_topic").toString());
        List<MarketTopic> topics = topicService.queryTopicRelated(id);
        List<MarketTopic> topicList = createRandoms(topics, limit);
        CommonData data = new CommonData();
        Integer page=1;
        data.setLimit(limit);
        data.setList(topicList);
        data.setPage(page);
        int total=(int) topics.stream().count();
        data.setTotal(total);
        int pages=total%limit==0?total/limit:total/limit+1;
        data.setPages(pages);
        return BaseRespVo.ok(data);
    }
    private static List<MarketTopic> createRandoms(List<MarketTopic> list, int n) {
        Map<Integer,String> map = new HashMap();
        List<MarketTopic> news = new ArrayList();
        if (list.size() <= n) {
            return list;
        } else {
            while (map.size() < n) {
                int random = (int)(Math.random() * list.size());
                if (!map.containsKey(random)) {
                    map.put(random, "");
                    news.add(list.get(random));
                }
            }
            return news;
        }
    }
}
